package com.ity.teamanagement.service.Impl;

import com.ity.teamanagement.code.CommonCode;
import com.ity.teamanagement.entity.TeaMessage;
import com.ity.teamanagement.entity.TeaQrCode;
import com.ity.teamanagement.entity.TeaRemarksMessage;
import com.ity.teamanagement.entity.Varieties;
import com.ity.teamanagement.entity.inputParam.BackAddTeaMessageParam;
import com.ity.teamanagement.entity.inputParam.BackUpdateTeaMessageParam;
import com.ity.teamanagement.entity.inputParam.BackUpdateTeaRemarksMessageParam;
import com.ity.teamanagement.entity.inputParam.ExTeaMessageParam;
import com.ity.teamanagement.entity.outputResult.ImgIdParam;
import com.ity.teamanagement.exception.ExceptionUtils;
import com.ity.teamanagement.mapper.QrCodeMapper;
import com.ity.teamanagement.mapper.TeaManagementMapper;
import com.ity.teamanagement.mapper.TeaSearchMapper;
import com.ity.teamanagement.service.QrCodeService;
import com.ity.teamanagement.service.TeaManagementService;
import com.ity.teamanagement.utils.EJBGenerator;
import com.ity.teamanagement.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author coderFu
 * @create 2021/5/30
 */
@Slf4j
@Service
public class TeaManagementServiceImpl implements TeaManagementService {

    @Resource
    private TeaManagementMapper teaManagementMapper;

    @Autowired
    private QrCodeService qrCodeService;

    @Autowired
    private QrCodeMapper qrCodeMapper;

    @Autowired
    private TeaSearchMapper teaSearchMapper;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void backAddNewTeaVariety(BackAddTeaMessageParam backAddTeaMessageParam) {
        if (backAddTeaMessageParam == null) {
            ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
        }
        //添加tea_message中的信息
        TeaMessage teaMessage = new TeaMessage();
        teaMessage.setChineseName(backAddTeaMessageParam.getChineseName());
        teaMessage.setLatinName(backAddTeaMessageParam.getLatinName());
        teaMessage.setGrowYear(backAddTeaMessageParam.getGrowYear());
        teaMessage.setAbstractMessage(backAddTeaMessageParam.getAbstractMessage());
        teaMessage.setCoverImgId(backAddTeaMessageParam.getCoverImgId());
        teaMessage.setGrade(backAddTeaMessageParam.getGrade());
        teaMessage.setProvince(backAddTeaMessageParam.getProvince());
        teaMessage.setCity(backAddTeaMessageParam.getCity());
        teaMessage.setCounty(backAddTeaMessageParam.getCounty());
        teaMessage.setAddress(backAddTeaMessageParam.getAddress());
        teaMessage.setVarietyIntroduce(backAddTeaMessageParam.getVarietyIntroduce());
        teaMessage.setAKeyId(backAddTeaMessageParam.getAKeyId());
        teaMessage.setRareVariety(1L);
        teaMessage.setCreateTime(new Date());
        Integer teaMessageCount = teaManagementMapper.addTeaMessage(teaMessage);
        if (teaMessageCount < 1) {
            ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
        }
        //添加备注表中的茶种信息
        List<ExTeaMessageParam> exTeaMessageParams = backAddTeaMessageParam.getExTeaMessageParams();
        System.out.println(exTeaMessageParams);
        if (exTeaMessageParams != null && exTeaMessageParams.size() >= 1) {
            List<TeaRemarksMessage> teaRemarksMessages = new ArrayList<>();
            for (ExTeaMessageParam exTeaMessageParam : exTeaMessageParams) {
                TeaRemarksMessage remarksMessage = new TeaRemarksMessage();
                remarksMessage.setContent(exTeaMessageParam.getContent());
                remarksMessage.setExKeyId(exTeaMessageParam.getExKeyId());
                remarksMessage.setTeaMessageId(teaMessage.getId());
                remarksMessage.setCreateTime(new Date());
                teaRemarksMessages.add(remarksMessage);
                System.out.println(teaMessage.getId());
            }
            Integer teaRemarksCount = teaManagementMapper.addRemarksTeaMessage(teaRemarksMessages);
            if (teaRemarksCount < 1) {
                ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
            }
        }
          //更新茶种图片表中的信息，补充上茶种id
        List<Long> teaImgParams = backAddTeaMessageParam.getImgIds();
        if(teaImgParams != null && teaImgParams.size()>0 ) {
            Integer teaImgUpdateCount = teaManagementMapper.updateTeaImgByKeyId(teaMessage.getId(), teaImgParams);
            if (teaImgUpdateCount < 1) {
                ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
            }
        }
         qrCodeService.produceOneQrCodeById(Collections.singletonList(teaMessage.getId()));
    }

    @Override
    public void backUpdateTeaMessageById(BackUpdateTeaMessageParam backUpdateTeaMessageParam) {
        if (backUpdateTeaMessageParam == null) {
            ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
        }
        TeaMessage teaMessage = new TeaMessage();
        teaMessage.setId(backUpdateTeaMessageParam.getId());
        teaMessage.setChineseName(backUpdateTeaMessageParam.getChineseName());
        teaMessage.setLatinName(backUpdateTeaMessageParam.getLatinName());
        teaMessage.setGrowYear(backUpdateTeaMessageParam.getGrowYear());
        teaMessage.setCoverImgId(backUpdateTeaMessageParam.getCoverImgId());
        teaMessage.setAbstractMessage(backUpdateTeaMessageParam.getAbstractMessage());
        teaMessage.setGrade(backUpdateTeaMessageParam.getGrade());
        teaMessage.setProvince(backUpdateTeaMessageParam.getProvince());
        teaMessage.setCity(backUpdateTeaMessageParam.getCity());
        teaMessage.setCounty(backUpdateTeaMessageParam.getCounty());
        teaMessage.setAddress(backUpdateTeaMessageParam.getAddress());
        teaMessage.setVarietyIntroduce(backUpdateTeaMessageParam.getVarietyIntroduce());
        teaMessage.setAKeyId(backUpdateTeaMessageParam.getAKeyId());
        teaMessage.setRareVariety(1L);
        teaMessage.setUpdateTime(new Date());
        Integer count = teaManagementMapper.updateTeaMessageById(teaMessage);
        if (count < 1) {
            ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
        }
        List<Long> teaImg = backUpdateTeaMessageParam.getIds();

        if (teaImg != null && teaImg.size() > 0) {
            Integer teaImgUpdateCount = teaManagementMapper.updateTeaImg(teaMessage.getId(), backUpdateTeaMessageParam.getIds());
            if (teaImgUpdateCount < 1) {
                ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
            }
        }
        TeaQrCode teaQrCode = qrCodeMapper.getTeaQrCodeByTeaId(teaMessage.getId());
        qrCodeService.deleteTeaQrCodeByIds(Collections.singletonList(teaQrCode.getQrImgId()));
        qrCodeService.produceOneQrCodeById(Collections.singletonList(teaMessage.getId()));
    }

    @Override
    public void backUpdateTeaRemarksMessageById(List<BackUpdateTeaRemarksMessageParam> backUpdateTeaRemarksMessageParams) {
       if ( backUpdateTeaRemarksMessageParams != null && backUpdateTeaRemarksMessageParams.size() != 0 ) {
           List<BackUpdateTeaRemarksMessageParam> updateTeaRemarksMessageParams = new ArrayList<>();
           List<TeaRemarksMessage> insertTeaRemarksMessageParams = new ArrayList<>();
           for (BackUpdateTeaRemarksMessageParam backUpdateTeaRemarksMessageParam : backUpdateTeaRemarksMessageParams) {
               if (backUpdateTeaRemarksMessageParam.getId() != null) {
                   updateTeaRemarksMessageParams.add(backUpdateTeaRemarksMessageParam);
               }
               EJBGenerator ejbGenerator = new EJBGenerator();
               if (backUpdateTeaRemarksMessageParam.getId() == null) {
                   TeaRemarksMessage teaRemarksMessage = ejbGenerator.convert(backUpdateTeaRemarksMessageParam, TeaRemarksMessage.class);
                   teaRemarksMessage.setCreateTime(new Date());
                   insertTeaRemarksMessageParams.add(teaRemarksMessage);
               }
           }
           System.out.println("更新执行开始");
           if (updateTeaRemarksMessageParams.size() != 0) {
               Integer count = teaManagementMapper.updateTeaRemarksMessageById(backUpdateTeaRemarksMessageParams);
               if (count < 1) {
                   ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
               }
           }
           System.out.println("更新执行结束");
           System.out.println("插入执行开始");
           if (insertTeaRemarksMessageParams.size() != 0) {
               Integer integer = teaManagementMapper.addRemarksTeaMessage(insertTeaRemarksMessageParams);
               if (integer < 1) {
                   ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
               }
           }
           System.out.println("插入执行结束");
       }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void backDeleteTeaMessageById(List<Long> ids) {
        if (ids.size() == 0) {
            ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
        }
        List<ImgIdParam> imgIdParams = teaManagementMapper.findCoverImgAndArId(ids);
        //封面图片组id
        List<Long> coverImgIds = imgIdParams.stream().map(ImgIdParam::getCoverImgId).collect(Collectors.toList());
        //文章图片组id
        List<Long> articleImgIds = imgIdParams.stream().map(ImgIdParam::getAKeyId).collect(Collectors.toList());
        //附加图片组id
        List<Long> exImgIds = teaManagementMapper.findExKeyIdById(ids);
        //将三个图片组id合并查询图片路径
        List<Long> allImgIds = new ArrayList<>();
        allImgIds.addAll(coverImgIds);
        allImgIds.addAll(exImgIds);
        allImgIds.addAll(articleImgIds);
        //附加图片路径
        List<String> imgPaths = teaManagementMapper.findImgPathByKeyId(allImgIds);
        //茶种图片（芽、叶等）组路径
        List<String> teaImgPaths = teaManagementMapper.findTeaImgPathById(ids);
        //将路径合并为所有图片路径
        imgPaths.addAll(teaImgPaths);
        //剩余删除图片方法没写，后面补上
        for (String path : imgPaths) {
            FileUtils.deleteFile(path);
        }
        //删除茶种记录
        Integer teaCount = teaManagementMapper.deleteTeaMessageById(ids);
        //删除茶种附加信息
        if (exImgIds.size() > 0) {
            Integer remarksTeaCount = teaManagementMapper.deleteRemarksTeaMessageById(ids);
            if (remarksTeaCount < 1) {
                ExceptionUtils.error(CommonCode.DELETE_ERROR);
            }
        }
        //当附加图片表有信息时，删除附加图片表记录
        if (allImgIds.size() > 0) {
            Integer otherImgCount = teaManagementMapper.deleteOtherImgId(allImgIds);
            if (otherImgCount < 1) {
                ExceptionUtils.error(CommonCode.DELETE_ERROR);
            }
        }
        //删除茶种图片（芽、叶）表信息记录
        if (teaImgPaths.size() > 0) {
            Integer teaPathCount = teaManagementMapper.deleteTeaImg(ids);
            if (teaPathCount < 1) {
                ExceptionUtils.error(CommonCode.DELETE_ERROR);
            }
        }
    }

    @Override
    public List<Varieties> findAllVariety() {
        return teaManagementMapper.findAllVariety();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void backDeleteTeaRemarkMessageById(List<Long> ids) {
        if (ids.size() == 0) {
            ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
        }
        List<Long> exKeyIdById = teaManagementMapper.findExKeyIdByIds(ids);
        //删除图片文件
        List<String> paths = teaManagementMapper.findImgPathByKeyId(exKeyIdById);
        if (paths.size()>0){
            for (String path : paths) {
                FileUtils.deleteFile(path);
            }
        }
        //删除附加茶种记录表信息
        Integer integer = teaManagementMapper.deleteRemarksTeaMessageByIds(ids);
        if (integer<1){
            ExceptionUtils.error(CommonCode.DELETE_ERROR);
        }
        //删除附加图片表数据
        Integer integer1 = teaManagementMapper.deleteOtherImgId(exKeyIdById);
        if (integer1<1){
            ExceptionUtils.error(CommonCode.DELETE_ERROR);
        }
    }
}
